//
//  Common.swift
//  YMPayUI
//
//  Created by youmy on 2018/11/19.
//  Copyright © 2018 youmyyoumy. All rights reserved.
//

import Foundation
import UIKit

/// 屏幕尺寸
let ym_screen_bounds = UIScreen.main.bounds

/// 屏幕大小
let ym_screen_size = UIScreen.main.bounds.size

/// 屏幕宽度
let ym_screen_width = UIScreen.main.bounds.width

/// 屏幕高度
let ym_screen_height = UIScreen.main.bounds.height

// 字体
/// 苹方-Regular
let PingFangSC_Regular = "PingFangSC-Regular"

/// 苹方-Medium
let PingFangSC_Medium = "PingFangSC-Medium"

let bundle = Bundle(path: Bundle.main.path(forResource: "RentFreeImages.bundle", ofType: nil) ?? "")


func resoucearrayFromFile(fileName: String, bundle:Bundle? = nil) -> [[String:Any]] {
    
    var jsonPath:String?
    
    if bundle != nil {
        jsonPath = bundle?.path(forResource: fileName, ofType: nil)
    }else{
        jsonPath = Bundle.main.path(forResource: fileName, ofType: nil)
    }
    
    guard let path = jsonPath else {
        return [[String: Any]]()
    }
    
    let data = try? Data(contentsOf: URL(fileURLWithPath: path))
    
    if data != nil {
        let arr = try? JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.allowFragments) as! Array<Dictionary<String, Any>>
        return arr ?? [[String: Any]]()
    }
    return [[String: Any]]()
}


///获取当前控制器
func currentVc() ->UIViewController{
    
    var vc = UIApplication.shared.keyWindow?.rootViewController
    
    if (vc?.isKind(of: UITabBarController.self))! {
        vc = (vc as! UITabBarController).selectedViewController
    }else if (vc?.isKind(of: UINavigationController.self))!{
        vc = (vc as! UINavigationController).visibleViewController
    }else if ((vc?.presentedViewController) != nil){
        vc =  vc?.presentedViewController
    }
    
    return vc!
    
}

extension Double {
    func roundTo(places: Int) -> Double {
        let divisor = pow(10.0, Double(places))
        return (self * divisor).rounded() / divisor
    }
}

extension UIImageView{
    func downloadedFrom(imageurl : String){
        if imageurl.isEmpty {
            return
        }
        let newUrl = imageurl.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
        //创建URL对象
        let url = URL(string: newUrl!)!
        //创建请求对象
        let request = URLRequest(url: url)
        
        let session = URLSession.shared
        let dataTask = session.dataTask(with: request, completionHandler: {
            (data, response, error) -> Void in
            if error != nil{
                print(error.debugDescription)
            }else{
                //将图片数据赋予UIImage
                let img = UIImage(data:data!)
                
                // 这里需要改UI，需要回到主线程
                DispatchQueue.main.async {
                    self.image = img
                }
                
            }
        }) as URLSessionTask
        
        //使用resume方法启动任务
        dataTask.resume()
    }
    
    func dowloadFromServer(url: URL, contentMode mode: UIView.ContentMode = .scaleAspectFit) {
        contentMode = mode
        URLSession.shared.dataTask(with: url) { data, response, error in
            guard
                let httpURLResponse = response as? HTTPURLResponse, httpURLResponse.statusCode == 200,
                let mimeType = response?.mimeType, mimeType.hasPrefix("image"),
                let data = data, error == nil,
                let image = UIImage(data: data)
                else { return }
            DispatchQueue.main.async() {
                self.image = image
            }
            }.resume()
    }
    
    func dowloadFromServer(link: String, contentMode mode: UIView.ContentMode = .scaleAspectFit) {
        guard let url = URL(string: link) else { return }
        dowloadFromServer(url: url, contentMode: mode)
    }
    
}
